package main

import (
	"bufio"
	"context"
	"flag"
	"fmt"
	pb "goGrpcTest/grpcCnf"
	"io"
	"log"
	"os"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

const (
	defaultName = "007"
)

var (
	addr = flag.String("addr", "localhost:50051", "the address to connect to")
	name = flag.String("name", defaultName, "Name to greet")
)

func uploadFile(client pb.GreeterClient, filename string) error {
	file, err := os.Open(filename)
	if err != nil {
		return fmt.Errorf("cannot open file: %v", err)
	}
	defer file.Close()

	stream, err := client.UploadFile(context.Background())
	if err != nil {
		return fmt.Errorf("cannot create upload stream: %v", err)
	}

	// 发送文件名
	if err := stream.Send(&pb.FileUploadRequest{
		Filename: filename,
		Content:  []byte{},
	}); err != nil {
		return fmt.Errorf("cannot send filename: %v", err)
	}

	// 读取并发送文件内容
	reader := bufio.NewReader(file)
	buffer := make([]byte, 1024) // 1KB 缓冲区

	for {
		n, err := reader.Read(buffer)
		if err == io.EOF {
			break
		}
		if err != nil {
			return fmt.Errorf("cannot read file: %v", err)
		}

		if err := stream.Send(&pb.FileUploadRequest{
			Filename: "", // 后续chunk不需要文件名
			Content:  buffer[:n],
		}); err != nil {
			return fmt.Errorf("cannot send chunk: %v", err)
		}
	}

	// 接收响应
	response, err := stream.CloseAndRecv()
	if err != nil {
		return fmt.Errorf("cannot receive response: %v", err)
	}

	log.Printf("Upload completed: %s", response.GetMessage())
	log.Printf("File type: %s, Size: %d bytes", response.GetFileType(), response.GetFileSize())
	return nil
}

func main() {
	// 命令行参数解析
	flag.Parse()
	// Set up a connection to the server.
	conn, err := grpc.NewClient(*addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c := pb.NewGreeterClient(conn)

	// 首先测试原有的SayHello功能
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	// 调用服务端函数
	r, err := c.SayHello(ctx, &pb.HelloRequest{Name: *name})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r.GetMessage())

	// 文件上传功能
	fmt.Println("\n=== File Upload Test ===")
	//fmt.Print("Enter file path to upload (or press Enter to skip): ")
	//scanner := bufio.NewScanner(os.Stdin)
	// if scanner.Scan() {
	filename := "C:\\1.jpg" //scanner.Text()
	if filename != "" {
		if err := uploadFile(c, filename); err != nil {
			log.Printf("Upload failed: %v", err)
		}
	} else {
		fmt.Println("File upload skipped.")
	}
	// }
}
